﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebLog.Db.Update
{
    internal class update_v2_4 : baseUpdateDatabase
    {
        public update_v2_4()
        {
            this.V = 2.4;
            this.Memo = "添加weblog 操作人姓名；添加键值对记录表（类似配置的作用，但是更广泛）";
            Task.Run(() =>
            {
                WebLogHelper.StatusWait.WaitStatus(WebLogStatus.TimerNotRun);
                while (true)
                {
                    DataTable data = SQLiteHelper.GetInstance().GetDataTable(@"
                    select Headers,id from  weblog
                    where realName ISNULL
                    order by id
                    LIMIT 0, 500");
                    if (data.Rows.Count == 0) break;
                    var rows = data.Select("Headers like '%ck_userrealname=%' and Headers like '%ck_userid=%'");
                    var idNames = new Dictionary<string, List<int>>();
                    Action<int, string> addUpdate = (id, key) =>
                    {
                        idNames.TryAdd(key, new List<int>());
                        idNames[key].Add(id);
                    };
                    foreach (DataRow row in data.Rows)
                    {
                        var headers = row[0].ToString();
                        var logId = int.Parse(row[1].ToString());
                        if (!rows.Contains(row))
                            headers = null;
                        addUpdate(logId, WebLogHelper.parseHeaders(headers));
                    }
                    var updates = new List<string>();
                    List<SQLiteParameter> parameters = new List<SQLiteParameter>();
                    foreach (var item in idNames)
                    {
                        parameters.Add(new SQLiteParameter("@p" + updates.Count, item.Key));
                        updates.Add(string.Format(@"update weblog set realName=@p{0} where id in ({1})"
                            , updates.Count, string.Join(',', item.Value)));
                    }
                    sqliteHelper.ExecuteNonQueryAsync(string.Join(";", updates), true, parameters.ToArray()).Wait();
                }
            });
        }
        internal override async Task UpdateAction()
        {
            await sqliteHelper.ExecuteNonQueryAsync(@"
                    DROP TABLE if exists weblogTmp;
                    create table if not exists weblogTmp(
                        id integer PRIMARY KEY autoincrement,                -- 设置主键
                        Path VARCHAR(500),Success BOOLEAN,ContentType VARCHAR(100),Headers TEXT,IsHttps BOOLEAN,Method VARCHAR(20),
                        Date DATETIME,Body TEXT,Query TEXT,Data TEXT,Message TEXT,Complete double,
                        RealName NVARCHAR(50)
                    );
                    INSERT INTO weblogTmp(path,Success,ContentType,Headers,IsHttps,Method,Date,Body,Query,Data,Message,Complete)
                        select path,Success,ContentType,Headers,IsHttps,Method,Date,Body,Query,Data,Message,Complete
                        from weblog;
                    drop table weblog;
                    alter table weblogTmp rename to weblog;
                    
                    create table if not exists KeyValues(
                        Key NVARCHAR(100),
                        Value TEXT
                    );");
        }
    }
}
